package com.sailor.config;

import com.sailor.pojo.User;
import com.sailor.service.Impl.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserServiceImpl userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //info.addStringPermission("user:add");
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();
        //从数据库拿到 并设置当前用户权限
        //info.addStringPermission(currentUser.getPerms());
        Set<String> functionalSet = new HashSet<>();
        functionalSet.add("user:add");
        functionalSet.add("user:update");
        info.setStringPermissions(functionalSet);
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证doGetAuthorizationInfo");

//        String name = "root";
//        String pass = "root";

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        User user = userService.getUserByname(userToken.getUsername());
        if (user == null) {
            return null;
        }
        Subject currentSession = SecurityUtils.getSubject();
        Session session = currentSession.getSession();
        session.setAttribute("loginUser", user);
        //密码 认证 shiro做
        return new SimpleAuthenticationInfo(user, user.getPwd(), "");
    }
}
